'use client';

import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Navbar from '@/components/Navbar';
import CategorySelector from '@/components/CategorySelector';
import Challenge from '@/components/Challenge';
import Leaderboard from '@/components/Leaderboard';

interface Category {
  id: string;
  name: string;
  parentId: string | null;
  children?: Category[];
}

export default function Dashboard() {
  const router = useRouter();
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [showChallenge, setShowChallenge] = useState(false);
  const [showLeaderboard, setShowLeaderboard] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [fillOnly, setFillOnly] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetchCategories();
    checkAuth();
  }, []);

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setShowMenu(false);
      }
    };

    if (showMenu) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showMenu]);

  const checkAuth = async () => {
    try {
      const res = await fetch('/api/auth/me');
      const data = await res.json();
      if (!data.success) {
        router.push('/');
      }
    } catch (error) {
      router.push('/');
    }
  };

  const fetchCategories = async () => {
    try {
      const res = await fetch('/api/categories');
      const data = await res.json();
      if (data.success) {
        setCategories(data.categories);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const handleStartChallenge = () => {
    if (!selectedCategory) {
      alert('请先选择一个分类');
      return;
    }
    setFillOnly(false);
    setShowChallenge(true);
    setShowLeaderboard(false);
  };

  const handleStartFillOnly = () => {
    if (!selectedCategory) {
      alert('请先选择一个分类');
      return;
    }
    setFillOnly(true);
    setShowChallenge(true);
    setShowLeaderboard(false);
  };

  const handleChallengeComplete = () => {
    setShowChallenge(false);
    fetchCategories(); // 刷新数据
  };

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <div className="container py-6">
        {!showChallenge ? (
          <div className="transition-all duration-500 ease-in-out space-y-6">
            {showLeaderboard ? (
              /* 排行榜内容 */
              <Leaderboard categoryId={selectedCategory} />
            ) : (
              <>
                {/* 操作按钮 */}
                <div className="flex gap-3 flex-wrap">
                  <button
                    className="px-6 py-3 rounded-xl bg-primary text-primary-foreground hover:bg-primary/90 transition-all duration-300 shadow-md hover:shadow-lg active:scale-[0.98] font-medium"
                    onClick={handleStartChallenge}
                  >
                    开始挑战
                  </button>
                  <button
                    className="px-6 py-3 rounded-xl bg-secondary text-secondary-foreground hover:bg-secondary/80 transition-all duration-300 shadow-sm hover:shadow-md active:scale-[0.98] font-medium"
                    onClick={handleStartFillOnly}
                  >
                    拼写纯享版模式
                  </button>
                </div>
                
                {/* 分类选择器 */}
                <CategorySelector
                  categories={categories}
                  selectedCategory={selectedCategory}
                  onSelectCategory={setSelectedCategory}
                />
              </>
            )}
          </div>
        ) : (
          <Challenge
            categoryId={selectedCategory!}
            onComplete={handleChallengeComplete}
            onCancel={() => setShowChallenge(false)}
            fillOnly={fillOnly}
          />
        )}
      </div>

      {/* 浮动菜单按钮 */}
      {!showChallenge && (
        <div ref={menuRef} className="fixed bottom-6 left-6 z-50">
          {/* 主按钮 */}
          <button
            onClick={() => setShowMenu(!showMenu)}
            className={`w-14 h-14 rounded-full bg-primary text-primary-foreground shadow-lg hover:shadow-xl transition-all duration-300 flex items-center justify-center ${
              showMenu ? 'rotate-45' : ''
            }`}
          >
            <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
            </svg>
          </button>

          {/* 悬浮菜单 */}
          {showMenu && (
            <div className="absolute bottom-16 left-0 space-y-3 animate-in fade-in slide-in-from-bottom-4 duration-200">
              {/* 挑战按钮 */}
              <button
                onClick={() => {
                  setShowLeaderboard(false);
                  setShowChallenge(false);
                  setShowMenu(false);
                }}
                className={`w-12 h-12 rounded-full bg-card border-2 shadow-lg hover:shadow-xl transition-all duration-300 flex items-center justify-center ${
                  !showLeaderboard
                    ? 'border-primary bg-primary/10'
                    : 'border-border hover:border-primary/50'
                }`}
                title="挑战"
              >
                <svg className="w-5 h-5 text-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
                </svg>
              </button>

              {/* 排行榜按钮 */}
              <button
                onClick={() => {
                  setShowLeaderboard(true);
                  setShowChallenge(false);
                  setShowMenu(false);
                }}
                className={`w-12 h-12 rounded-full bg-card border-2 shadow-lg hover:shadow-xl transition-all duration-300 flex items-center justify-center ${
                  showLeaderboard
                    ? 'border-primary bg-primary/10'
                    : 'border-border hover:border-primary/50'
                }`}
                title="排行榜"
              >
                <svg className="w-5 h-5 text-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                </svg>
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

